package com.jwds.digital.bios.business.service.service.dispatch.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwds.digital.bios.business.core.exceptions.RecordNotFoundException;
import com.jwds.digital.bios.business.core.infrastructure.dto.dispatch.DispatchConfiguratReqDTO;
import com.jwds.digital.bios.business.core.infrastructure.dto.dispatch.DispatchRuleReqDTO;
import com.jwds.digital.bios.business.core.infrastructure.dto.dispatch.assembler.DispatchConfiguratAssembler;
import com.jwds.digital.bios.business.core.infrastructure.dto.feign.BasicStockBinReqDTO;
import com.jwds.digital.bios.business.core.infrastructure.entity.dispatch.DispatchConfigurat;
import com.jwds.digital.bios.business.core.infrastructure.entity.dispatch.DispatchRule;
import com.jwds.digital.bios.business.core.infrastructure.mapper.dispatch.DispatchConfiguratMapper;
import com.jwds.digital.bios.business.core.infrastructure.mapper.dispatch.DispatchRuleMapper;
import com.jwds.digital.bios.business.core.infrastructure.vo.belt.BeltRouteTargetHisRespVO;
import com.jwds.digital.bios.business.core.infrastructure.vo.dispatch.DispatchConfiguratRespVO;
import com.jwds.digital.bios.business.core.infrastructure.vo.feign.BasicStockBinRespVO;
import com.jwds.digital.bios.business.core.infrastructure.vo.feign.FlowBasicRespVO;
import com.jwds.digital.bios.business.service.service.dispatch.IDispatchConfiguratService;
import com.jwds.tdc.framework.application.lib.page.PageRequest;
import com.jwds.tdc.framework.application.lib.page.PageResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 规则配置实现类
 *
 * @author 林柏云
 * @date 2024-10-24
 */
@Slf4j
@Service
public class DispatchConfiguratServiceImpl extends ServiceImpl<DispatchConfiguratMapper, DispatchConfigurat> implements IDispatchConfiguratService {

    @Autowired
    private DispatchConfiguratMapper baseMapper;

    @Autowired
    private DispatchRuleMapper dispatchRuleMapper;

    @Override
    public DispatchConfiguratRespVO queryById(Long id) {
        if (id == null) {
            return null;
        }
        DispatchConfigurat entity = baseMapper.selectById(id);
        // 通过id查询规则内容
        LambdaQueryWrapper<DispatchRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DispatchRule::getRuleCode, entity.getRuleCode());
        List<DispatchRule> dispatchRuleList = dispatchRuleMapper.selectList(wrapper);
        entity.setDispatchRuleList(dispatchRuleList);
        DispatchRule dto=dispatchRuleMapper.selectById(entity.getRuleCode());
        DispatchConfiguratRespVO dispatchConfiguratRespVO = DispatchConfiguratAssembler.entity2dto(entity);
        dispatchConfiguratRespVO.setGeneralRule(dto.getRuleCode()+","+dto.getRuleName()+","+dto.getRuleDescription());
        return dispatchConfiguratRespVO;
    }

    @Override
    public PageResponse<DispatchConfiguratRespVO> page(PageRequest<DispatchConfiguratReqDTO> request) {
        DispatchConfiguratReqDTO condition = request.getQueryCondition();
        Page<DispatchConfiguratRespVO> page = new Page<>(request.getPageIndex(), request.getPageSize());
        IPage<DispatchConfiguratRespVO> pageData = baseMapper.pageQuery(page, condition);
        PageResponse<DispatchConfiguratRespVO> dispatchConfiguratRespVOPageResponse = new PageResponse<>((Page<?>) pageData, pageData.getRecords());
        dispatchConfiguratRespVOPageResponse.getLists().stream().forEach(dispatchConfiguratRespVO -> {
            DispatchRule dto=dispatchRuleMapper.selectById(dispatchConfiguratRespVO.getRuleCode());
            dispatchConfiguratRespVO.setGeneralRule(dto.getRuleCode()+","+dto.getRuleName()+","+dto.getRuleDescription());
        });

        return dispatchConfiguratRespVOPageResponse;
    }


    @Override
    public void add(DispatchConfiguratReqDTO reqDto) {
        List<DispatchConfigurat> entityList = baseMapper.selectList(null);
        for (DispatchConfigurat entity : entityList) {
            if (entity.getRuleCode().equals(reqDto.getRuleCode())) {
                throw new RuntimeException("规则编码重复");
            } else if (entity.getGroupCode().equals(reqDto.getGroupCode())) {
                throw new RuntimeException("料条编码重复");
            }
        }
        DispatchConfigurat entity = DispatchConfiguratAssembler.dto2entity(reqDto);
        baseMapper.insert(entity);
        // 新增规则内容
        if (entity.getRuleCode()==null){
            for (DispatchRule dispatchRule : entity.getDispatchRuleList()) {
                dispatchRuleMapper.insert(dispatchRule);
            }
        }
    }

    @Override
    public void update(DispatchConfiguratReqDTO reqDto) {
        DispatchConfigurat oldEntity = baseMapper.selectById(reqDto.getId());
        if (oldEntity == null) {
            throw new RecordNotFoundException();
        }
        DispatchConfigurat newEntity = DispatchConfiguratAssembler.dto2entity(reqDto, oldEntity);
        baseMapper.updateById(newEntity);
        if (newEntity.getRuleCode()==null){
            // 修改规则内容
            LambdaQueryWrapper<DispatchRule> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DispatchRule::getRuleCode, newEntity.getRuleCode());
            dispatchRuleMapper.delete(wrapper);
            DispatchRule entity = dispatchRuleMapper.selectById(newEntity.getRuleCode());
            List<DispatchRule> dispatchRuleList =new ArrayList<>();
            for (DispatchRule dispatchRule : reqDto.getDispatchRuleList()) {
                dispatchRule.setGeneralRule(entity.getGeneralRule());
                dispatchRule.setRuleCode(entity.getRuleCode());
                dispatchRule.setRuleName(entity.getRuleName());
                dispatchRule.setRuleDescription(entity.getRuleDescription());
                dispatchRule.setRulePriority(entity.getRulePriority());
                dispatchRule.setRuleCategory(entity.getRuleCategory());
                dispatchRuleList.add(dispatchRule);
            }
            newEntity.setDispatchRuleList(dispatchRuleList);
            for (DispatchRule dispatchRule : newEntity.getDispatchRuleList()) {
                dispatchRuleMapper.insert(dispatchRule);
            }
        }
    }

    @Override
    public void delete(Long id) {
        DispatchConfigurat oldEntity = baseMapper.selectById(id);
        if (oldEntity == null) {
            throw new RecordNotFoundException();
        }
        baseMapper.deleteById(id);
        // 删除规则内容
        DispatchConfiguratRespVO DispatchConfigList = baseMapper.queryById(id);
        LambdaQueryWrapper<DispatchRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DispatchRule::getRuleCode, DispatchConfigList.getRuleCode());
        dispatchRuleMapper.delete(wrapper);
    }


    @Override
    public List<BasicStockBinRespVO> ScraperMachine(List<BasicStockBinRespVO> list) {
        List<BasicStockBinRespVO> collect = list.stream().sorted(Comparator.comparing(BasicStockBinRespVO::getState)).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<BasicStockBinRespVO> PreIngredientWarehouse(List<BasicStockBinRespVO> list) {
        List<BasicStockBinRespVO> collect = list.stream().sorted(Comparator.comparing(BasicStockBinRespVO::getUpperLimit)).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<BasicStockBinRespVO> ScraperMachineAndBin(List<BasicStockBinReqDTO> list) {
        List<BasicStockBinRespVO> basicStockBinRespVO = new ArrayList<>();
        List<BasicStockBinReqDTO> collect = list.stream().sorted(Comparator.comparing(BasicStockBinReqDTO::getInventory)).collect(Collectors.toList());
        BeanUtils.copyProperties(basicStockBinRespVO, collect);

        return basicStockBinRespVO;
    }

    @Override
    public List<BasicStockBinRespVO> InsufficientSilo(List<BasicStockBinReqDTO> list) {
        List<BasicStockBinRespVO> basicStockBinRespVO = new ArrayList<>();
        List<BasicStockBinReqDTO> collect = list.stream().sorted(Comparator.comparing(BasicStockBinReqDTO::getSafeInventory).reversed()).collect(Collectors.toList());
        BeanUtils.copyProperties(basicStockBinRespVO, collect);
        return basicStockBinRespVO;
    }

    @Override
    public List<BeltRouteTargetHisRespVO> LineEnergy(List<FlowBasicRespVO> list) {
        return baseMapper.LineEnergy(list);
    }

    @Override
    public List<BasicStockBinRespVO> DispatchMaterial(List<BasicStockBinReqDTO> list) {
        List<BasicStockBinRespVO> basicStockBinRespVO = new ArrayList<>();
        List<BasicStockBinReqDTO> collect = (List<BasicStockBinReqDTO>) list.stream().filter(e->e.getMaterialName().equals(list.stream().map(BasicStockBinReqDTO::getMaterialName).collect(Collectors.toList())));
        BeanUtils.copyProperties(basicStockBinRespVO, collect);
        return basicStockBinRespVO;
    }


}
